﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace HDS.Common.Helper
{
    public static class XmlHelper
    {
        /// <summary>
        /// 替换xml特殊字符
        /// </summary>
        /// <param name="sourse"></param>
        /// <returns></returns>
        public static string XmlReplace(this string source)
        {
            if (string.IsNullOrEmpty(source))
                return source;

            var sNotation1 = new string[] { "&", "<", ">", "\"", "'" };

            var dNotation = new string[] { "&amp;", "&lt;", "&gt;", "&quot;", "&apos;" };

            for (int i = 0; i < sNotation1.Length; i++)
            {
                source = source.Replace(sNotation1[i], dNotation[i]);
            }
            return source;
        }

        /// <summary>
        /// 包裹CDATA
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string XmlAddCDATA(this string source)
        {
            if (string.IsNullOrEmpty(source))
                return source;

            return string.Format("<![CDATA[{0}]]>", source);
        }

        public static string SelectSingleNodeValue(this XmlNode xmlNode, string xPath)
        {
            if (xmlNode == null)
                return string.Empty;

            XmlNode selectNode = xmlNode.SelectSingleNode(xPath);
            if (selectNode == null)
                return string.Empty;

            return selectNode.InnerText;
        }

        public static string SelectSingleNodeValue(this XmlNode xmlNode, string xPath, XmlNamespaceManager nsmgr)
        {
            if (xmlNode == null)
                return string.Empty;

            XmlNode selectNode = xmlNode.SelectSingleNode(xPath, nsmgr);
            if (selectNode == null)
                return string.Empty;

            return selectNode.InnerText;
        }

        public static string GetAttributesValue(this XmlNode xmlNode, string AttributeName)
        {
            if (xmlNode == null)
                return string.Empty;

            var attr = xmlNode.Attributes[AttributeName];
            if (attr == null)
                return string.Empty;

            return attr.Value;
        }
    }
}
